<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class CheckAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        //未登录返回登录页
        $bool = auth()->check();

        if(!$bool){
            return redirect(route('login'))->withErrors('请先登录');
        }

        $nodes = session('admin_auths');
        if($nodes !== true){
            //获取当前路由
            $routeName = $request->route()->getName();
            $currntRouteName = array_filter(array_merge($nodes,config('rbac.allow_route')));
            if(!in_array($routeName,$currntRouteName)){

                return redirect(route('admin.error'));
            }
        }

        return $next($request);
    }
}
